// --------------------------------------------------------------------------------------------------------------------
// <copyright file="KukaLBR4MoveToCandlePositionController.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Robotics.Hardware.KukaLBR
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;

    using Microsoft.Robotics.Manipulation;
    using Microsoft.Robotics.Manipulation.ControllerStateMachine;
    using Microsoft.Robotics.Numerics;

    using LBR4 = Microsoft.Robotics.Hardware.KukaLBR.KukaLBR4PlusCsharpDefinitionsNativeMethods;

    /// <summary>
    /// Controller for joint position control
    /// </summary>
    public class KukaLBR4MoveToCandlePositionController : KukaLBR4Controller
    {
        /// <summary>
        /// Controller state machine description cache
        /// </summary>
        private static ControllerStateMachineDescription csmdCache;

        /// <summary>
        /// Determines if we have a cached copy of the controller state machine description available
        /// </summary>
        private static bool haveCachedCsmd = false;

        /// <summary>
        /// max joint velocity
        /// </summary>
        private RegisterID jointVelocityRegister;

        /// <summary>
        /// cycle time step in millisecond
        /// </summary>
        private RegisterID cycleTimeInMsRegister;

        /// <summary>
        /// Register that stores the result of computing the actual commanded joint
        /// position.  This should be computed by getting the commanded joint position
        /// reported by FRI and applying the offset reported by FRI
        /// </summary>
        private RegisterID commandedJointPositionResultRegister;

        /// <summary>
        /// Register that stores the value indicating that FRI is in the command state.
        /// </summary>
        private RegisterID friCmdStateValueRegister;

        /// <summary>
        /// Initializes a new instance of the <see cref="KukaLBR4MoveToCandlePositionController" /> class
        /// </summary>
        /// <param name="registerManager">the register manager</param>
        /// <param name="jointVelocityInRadPerSec">max joint velocity</param>
        /// <param name="timeStepInMsec">time step</param>
        public KukaLBR4MoveToCandlePositionController(
            KukaLBR4WorkingRegisterManager registerManager,
            double jointVelocityInRadPerSec,
            double timeStepInMsec) :
            base(registerManager)
        {
            this.commandedJointPositionResultRegister = RegisterID.NewWorkingRegister(
                this.RegisterManager.GetNextRegisterID(KukaLBR4WorkingRegisterManager.RegisterValueTypes.JointVector));

            this.jointVelocityRegister = RegisterID.NewWorkingRegister(
                this.RegisterManager.GetNextRegisterID(KukaLBR4WorkingRegisterManager.RegisterValueTypes.Scalar));

            this.cycleTimeInMsRegister = RegisterID.NewWorkingRegister(
                this.RegisterManager.GetNextRegisterID(KukaLBR4WorkingRegisterManager.RegisterValueTypes.Scalar));

            this.friCmdStateValueRegister = RegisterID.NewWorkingRegister(
                this.RegisterManager.GetNextRegisterID(KukaLBR4WorkingRegisterManager.RegisterValueTypes.Scalar));

            // CMD state value
            this.WorkingRegisterArray.Registers[this.friCmdStateValueRegister.RegisterNumber][0] = 2;

            this.WorkingRegisterArray.Registers[this.jointVelocityRegister.RegisterNumber][0] = jointVelocityInRadPerSec;
            this.WorkingRegisterArray.Registers[this.cycleTimeInMsRegister.RegisterNumber][0] = timeStepInMsec;
        }

        /// <summary>
        /// Builds a state machine controller
        /// </summary>
        /// <returns>A state machine based controller</returns>
        public new ControllerStateMachineDescription BuildStateMachineDescription()
        {
            if (!haveCachedCsmd)
            {
                csmdCache = base.BuildStateMachineDescription();
                haveCachedCsmd = true;
            }

            return csmdCache;
        }

        /// <summary>
        /// Builds a state that generates a small step in joint space towards our goal
        /// </summary>
        /// <param name="commandedJointPositionResultRegister">current joint</param>
        /// <param name="jointVelocityRegister">maximum joint velocity in rad/sec</param>
        /// <param name="cycleTimeInMsRegister">fri cycle time</param>
        /// <returns>a controller state machine state</returns>
        protected static State BuildMoveToCandleState(
            RegisterID commandedJointPositionResultRegister,
            RegisterID jointVelocityRegister,
            RegisterID cycleTimeInMsRegister)
        {
            ControllerOperation[] operationsList = new ControllerOperation[1];

            // operation 0 - interpolate
            // we interpolate using
            // pre-defined interpolation function (SimpleJointInterpolationOp) to compute the next
            // joint position for the control time step
            RegisterID[] operation2Operands = new RegisterID[3];
            operation2Operands[0] = new RegisterID(
                RegisterTypes.Feedback,
                (int)LBR4.KukaLBR4PlusFeedbackRegisters.LastIssuedJointPositionCommandRegister);
            operation2Operands[1] = jointVelocityRegister;
            operation2Operands[2] = cycleTimeInMsRegister;

            operationsList[0] = new ControllerOperation(
                (int)LBR4.KukaLBR4Operations.GetJointAnglesForMotionToCandleAtConstantRate,
                new RegisterID(
                    RegisterTypes.Working,
                    (int)LBR4.KukaLBR4PlusWorkingRegisters.JointPositionCommandRegister),
                    operation2Operands);

            return new State(
                (int)LBR4.ControlModes.JointPositionControlMode,
                operationsList,
                new Transition[0],
                new Transition[0]);
        }

        /// <summary>
        /// Builds the controller state machine used by this controller.
        /// </summary>
        /// <returns>A controller state machine.</returns>
        protected override ControllerStateMachine BuildControllerStateMachine()
        {
            const int SynchronizationState = 0;
            const int MoveToCandleState = 1;

            ControllerStateMachine csm = new ControllerStateMachine();

            State[] stateArray = new State[2];

            stateArray[SynchronizationState] =
                KukaLBR4JointPositionController.BuildSynchronizeFRIJointPositionState(this.commandedJointPositionResultRegister);

            stateArray[MoveToCandleState] =
                BuildMoveToCandleState(
                commandedJointPositionResultRegister:
                this.commandedJointPositionResultRegister,
                jointVelocityRegister:
                this.jointVelocityRegister,
                cycleTimeInMsRegister:
                this.cycleTimeInMsRegister);

            csm.States = new List<State>(stateArray);

            // create a transition from the synchronization state to the interpolation state when
            // the state of the FRI connection reaches the desired value in Scalar1 (typically 2,
            // as this indicates command state -- a FRI error will result if we transition to the
            // interpolation state when the FRI connection is not in the CMD state).
            RegisterID[] transitionOnFriCmdOperands = new RegisterID[2];
            transitionOnFriCmdOperands[0] =
                this.friCmdStateValueRegister;
            transitionOnFriCmdOperands[1] =
                RegisterID.NewFeedbackRegister((int)LBR4.KukaLBR4PlusFeedbackRegisters.FRIStateRegister);

            csm.States[SynchronizationState].TransitionsToEvaluateAfterDefaults = new Transition[1];

            csm.States[SynchronizationState].TransitionsToEvaluateAfterDefaults[0] = new Transition(
                csm.States[MoveToCandleState],
                (int)LBR4.KukaLBR4Operations.AreScalarsEqualOp,
                transitionOnFriCmdOperands,
                new ControllerOperation[0]);

            return csm;
        }
    }
}
